import json
import random

import requests
from celery import shared_task

from Admin.models import RemoteProblem
from Problems.models import ProblemTag, Problem
from Robots.models import RemoteOJ


def random_dark_hex_color():
    r = random.randint(0, 127)
    g = random.randint(0, 127)
    b = random.randint(0, 127)
    return "#{:02x}{:02x}{:02x}".format(r, g, b)


@shared_task(bind=True)
def get_cf_problems(self):
    response = requests.get('https://codeforces.com/api/problemset.problems', headers={'Accept': 'application/json',
                                                                                       'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0'})

    data = json.loads(response.text).get('result')
    problems = data.get('problems')
    problemStatistics = data.get('problemStatistics')

    remote_oj = RemoteOJ.objects.get(name="CF")

    # 添加新题目和更新
    for problem, statistics in zip(problems, problemStatistics):
        print("正在添加问题", problem['name'], statistics['solvedCount'])
        try:
            record = RemoteProblem.objects.create(name=problem['name'],
                                                  remote_oj=remote_oj,
                                                  rating=problem.get('rating') if problem.get('rating') else 0,
                                                  remote_id=str(problem['contestId']) + problem['index'],
                                                  remote_url='https://codeforces.com/contest/' + str(
                                                      problem['contestId']) + '/problem/' + problem['index'],
                                                  solvedCount=statistics['solvedCount'],
                                                  is_get_problem_success=False,
                                                  )
        except Exception as e:
            print(e)
            break

        tags = problem.get('tags')
        for tag in tags:
            try:
                record.tags.add(ProblemTag.objects.get(name=tag))
                print("添加标签：", tag)
            except ProblemTag.DoesNotExist:
                pass
        if record.tags.count() == 0:
            record.tags.add(ProblemTag.objects.get(name='None'))
        record.save()

    for problem, statistics in zip(problems, problemStatistics):
        print("正在更新问题", problem['name'])
        try:
            remote_problem = RemoteProblem.objects.get(remote_id=str(problem['contestId']) + problem['index'])
        except RemoteProblem.DoesNotExist:
            continue
        if Problem.objects.filter(remote_oj__name="CF", remote_id=remote_problem.remote_id).exists():
            remote_problem.is_get_problem_success = True
        else:
            remote_problem.is_get_problem_success = False
        if problem.get('rating'):
            remote_problem.rating = problem.get('rating')
        else:
            remote_problem.rating = 0
        if statistics.get('solvedCount'):
            remote_problem.solvedCount = statistics.get('solvedCount')
        remote_problem.save()


@shared_task(bind=True)
def get_hdu_problems(self):
    print("正在更新 HDu 的题目")
    pass
